#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from __future__ import absolute_import
from __future__ import print_function
import rospy
from geometry_msgs.msg import Twist
# from std_msgs.msg import Float32
import sys, select, os
import tty, termios

BURGER_MAX_LIN_VEL = 0.10
BURGER_MAX_ANG_VEL = 0.3

WAFFLE_MAX_LIN_VEL = 0.10
WAFFLE_MAX_ANG_VEL = 0.3

LIN_VEL_STEP_SIZE = 0.02
ANG_VEL_STEP_SIZE = 0.1

FOMATION_CHANGE_SIZE = 0.2
MAX_FOMATION_CHANGE = 1

msg = """
Control Your TurtleBot3!
---------------------------
Moving around:
        w
   a    s    d
        x

w/x : increase/decrease linear velocity (Burger : ~ 0.22, Waffle and Waffle Pi : ~ 0.26)
a/d : increase/decrease angular velocity (Burger : ~ 2.84, Waffle and Waffle Pi : ~ 1.82)

space key, s : force stop

CTRL-C to quit
"""

e = """
Communications Failed
"""

def getKey():
    # 把输入文件描述符模式改为raw,然后直接调用操作系的IO接口,监控所有带fileno()方法的文件句柄
    # tty.setraw():将文件描述符fd模式更改为raw
    # fileno():返回一个整形的文件描述符(fd)
    tty.setraw(sys.stdin.fileno())
     # select():直接调用操作系统的IO接口，它监控所有带fileon()方法的文件句柄
    rlist, _, _ = select.select([sys.stdin], [], [], 0.1)
    if rlist:
        key = sys.stdin.read(1) # 只读取一个字节
    else:
        key = ''
    # termios该模块提供了一个用于tty I / O控制的POSIX调用的接口
    # tcsetattr:从属性设置文件描述符fd的tty属性
    # 参数二when: 参数确定属性何时发生更改：TCSANOW立即更改，TCSADRAIN在传输所有排队输出后更改，
    # 或TCSAFLUSH在传输所有排队输出并丢弃所有排队输入后更改
    termios.tcsetattr(sys.stdin, termios.TCSADRAIN, settings)
    return key

def vels(target_linear_vel, target_angular_vel, formation_size):
    return "currently:\tlinear vel %s\t angular vel %s\t fomation changed %s\t " % (target_linear_vel,target_angular_vel,formation_size)

def makeSimpleProfile(output, input, slop):
    if input > output:
        output = min( input, output + slop )
    elif input < output:
        output = max( input, output - slop )
    else:
        output = input

    return output

def constrain(input, low, high):
    if input < low:
      input = low
    elif input > high:
      input = high
    else:
      input = input

    return input

def checkLinearLimitVelocity(vel):
    if turtlebot3_model == "burger":
      vel = constrain(vel, 0.0 , BURGER_MAX_LIN_VEL)
    elif turtlebot3_model == "waffle" or turtlebot3_model == "waffle_pi":
      vel = constrain(vel, 0.0 , WAFFLE_MAX_LIN_VEL)
    else:
      vel = constrain(vel, 0.0 , BURGER_MAX_LIN_VEL)

    return vel

def checkFomationSize(vel):
    if vel < -MAX_FOMATION_CHANGE:
        vel = -MAX_FOMATION_CHANGE
    elif vel > MAX_FOMATION_CHANGE:
        vel = MAX_FOMATION_CHANGE
    else:
        vel = vel
    return vel

def checkAngularLimitVelocity(vel):
    if turtlebot3_model == "burger":
      vel = constrain(vel, -BURGER_MAX_ANG_VEL, BURGER_MAX_ANG_VEL)
    elif turtlebot3_model == "waffle" or turtlebot3_model == "waffle_pi":
      vel = constrain(vel, -WAFFLE_MAX_ANG_VEL, WAFFLE_MAX_ANG_VEL)
    else:
      vel = constrain(vel, -BURGER_MAX_ANG_VEL, BURGER_MAX_ANG_VEL)

    return vel

if __name__=="__main__":
    # tcgetattr():返回包含文件描述符fd的tty属性的列表
    settings = termios.tcgetattr(sys.stdin)

    rospy.init_node('cwm_interface')
    # pub = rospy.Publisher('/tb3_1/cmd_vel', Twist, queue_size=10)
    pub = rospy.Publisher('/cmd_user', Twist, queue_size=10)
    # pub = rospy.Publisher('tb3_0/cmd_vel', Twist, queue_size=10)

    turtlebot3_model = rospy.get_param("model", "waffle_pi")

    status = 0
    target_linear_vel   = 0.0
    target_angular_vel  = 0.0
    control_linear_vel  = 0.0
    control_angular_vel = 0.0
    formation_size = 0.0

    try:
        print(msg)
        while(1):
            key = getKey()
            if key == 'w' :
                target_linear_vel = checkLinearLimitVelocity(target_linear_vel + LIN_VEL_STEP_SIZE)
                status = status + 1
                print((vels(target_linear_vel,target_angular_vel,formation_size)))
            elif key == 'x' :
                target_linear_vel = checkLinearLimitVelocity(target_linear_vel - LIN_VEL_STEP_SIZE)
                status = status + 1
                print((vels(target_linear_vel,target_angular_vel,formation_size)))
            elif key == 'a' :
                target_angular_vel = checkAngularLimitVelocity(target_angular_vel + ANG_VEL_STEP_SIZE)
                status = status + 1
                print((vels(target_linear_vel,target_angular_vel,formation_size)))
            elif key == 'd' :
                target_angular_vel = checkAngularLimitVelocity(target_angular_vel - ANG_VEL_STEP_SIZE)
                status = status + 1
                print((vels(target_linear_vel,target_angular_vel,formation_size)))
            elif key == 'q' : # 缩小
                formation_size = checkFomationSize(formation_size - FOMATION_CHANGE_SIZE)
                print((vels(target_linear_vel,target_angular_vel,formation_size)))
            elif key == 'z' : # 放大
                formation_size = checkFomationSize(formation_size + FOMATION_CHANGE_SIZE)
                print((vels(target_linear_vel,target_angular_vel,formation_size)))
            elif key == ' ' or key == 's' :
                target_linear_vel   = 0.0
                control_linear_vel  = 0.0
                target_angular_vel  = 0.0
                control_angular_vel = 0.0
                print((vels(target_linear_vel, target_angular_vel,formation_size)))
            else:
                if (key == '\x03'):
                    break

            if status == 20 :
                print(msg)
                status = 0

            twist = Twist()

            # control_linear_vel = makeSimpleProfile(control_linear_vel, target_linear_vel, (LIN_VEL_STEP_SIZE/2.0))
            control_linear_vel = target_linear_vel
            twist.linear.x = control_linear_vel; twist.linear.y = formation_size; twist.linear.z = 0.0

            # control_angular_vel = makeSimpleProfile(control_angular_vel, target_angular_vel, (ANG_VEL_STEP_SIZE/2.0))
            control_angular_vel = target_angular_vel
            twist.angular.x = 0.0; twist.angular.y = 0.0; twist.angular.z = control_angular_vel

            pub.publish(twist)

    except:
        print(e)

    finally:
        twist = Twist()
        twist.linear.x = 0.0; twist.linear.y = formation_size; twist.linear.z = 0.0
        twist.angular.x = 0.0; twist.angular.y = 0.0; twist.angular.z = 0.0
        pub.publish(twist)

    if os.name != 'nt':
        termios.tcsetattr(sys.stdin, termios.TCSADRAIN, settings)
